package framework.async
{
	import framework.Utils;

	import mx.core.mx_internal;
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	use namespace mx_internal;

	public class ChainResponder implements IResponder
	{
		public var chain:Array;

		public var token:AsyncToken;

		public var results:Array = [];

		public function ChainResponder()
		{
			token = new AsyncToken(null);
		}

		public function result(data:Object):void
		{
			var e:ResultEvent = ResultEvent(data);
			results.push(e.result);
			if (chain.length)
			{
				Utils.callLater(chainInternal, [ this ]);
			}
			else
			{
				var re:ResultEvent = ResultEvent.createEvent(e.result, token);
				token.results = results;
				token.mx_internal::applyResult(re);
			}
		}

		public function fault(info:Object):void
		{
			var e:FaultEvent = FaultEvent(info);
			token.results = results;
			token.mx_internal::applyFault(e);
		}

	}
}